<?php

class Controller_Maillist extends Controller_Template
{

	public function actionIndex()
	{
		$this->template->title = $this->settings['title'];
		$this->template->content = new View('index/maillist');
		$form = new Form('subscribe');
		$form->text('email', 'E-mail')->rule('required')->rule('email')->callback('emailCheck');
		function emailCheck($field) {
			Model_Table::instance('mailList')->keys['string'] = 'email';
			Model_Table::instance('mailList')->primaryKey = 'email';
			if (Model_Table::instance('mailList')->exists($field->value)) {
				$field->error(Text::DUPLICATE_KEY);
			}
		}
		$form->text('name', 'Your name')->rule('required')->attribute('size', 40)->rule('maxLength', 64);
		$form->submit('submit', 'Subscribe');
		$this->addStyle('/styles/autoform.css');
		$this->template->content->form = $form;
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				$values = $form->getValues();
				MailList::getInstance()->subscribe($values);
				$this->template->content->message = 'Thank you. Please confirm your subscription by following link in your confirmation email.';
			}
		}
	}

	public function actionConfirm($token) {
		$this->template->content = new View('index/confirmation');
		if (Model::factory('mailList')->confirm($token)) {
			$this->template->content->result = true;
		} else {
			$this->template->content->result = false;
		}
	}
}